package com.adtech.farmProducts.activities.activity;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.adtech.common.Common;
import com.adtech.common.http.AsyncHttpPostFormData;
import com.adtech.common.http.AsyncHttpResponse;
import com.adtech.common.http.AsyncOkHttpClient;
import com.adtech.common.http.AsyncResponseHandler;
import com.adtech.common.model.RspModel;
import com.adtech.common.utils.AccountManagers;
import com.adtech.common.utils.FileUtils;
import com.adtech.common.utils.TimeUtil;
import com.adtech.common.widgets.load.LoadFactory;
import com.adtech.common.widgets.load.core.LoadManager;
import com.adtech.common.widgets.load.view.AbsView;
import com.adtech.farmProducts.App;
import com.adtech.farmProducts.R;
import com.adtech.farmProducts.base.BaseNfcActivity;
import com.adtech.farmProducts.model.FUserInfo;
import com.adtech.farmProducts.model.NFCResult;
import com.adtech.farmProducts.model.SourceInfo;
import com.adtech.farmProducts.utils.Constants;
import com.adtech.farmProducts.widget.ErrorView;
import com.adtech.farmProducts.widget.LoadingView;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.yalantis.ucrop.UCrop;

import java.io.IOException;
import java.lang.reflect.Type;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Time:2020/6/20
 * Created by xiaocz
 * Describe 封箱
 */
public class UpdateTag2Activity extends BaseNfcActivity {

    @BindView(R.id.layout_base)
    LinearLayout layout_base;
    @BindView(R.id.edit_gs_name)
    TextView edit_gs_name;
    @BindView(R.id.tv_address)
    TextView tv_address;
    @BindView(R.id.tv_time)
    TextView tv_time;

    @BindView(R.id.tv_code)
    TextView tv_code;
    @BindView(R.id.tv_name)
    TextView tv_name;
    @BindView(R.id.tv_unit)
    TextView tv_unit;
    @BindView(R.id.tv_weight)
    TextView tv_weight;
    @BindView(R.id.layout_camera)
    LinearLayout layout_camera;

    /**
     * DATA
     */
    private LoadManager mLoadManager;
    private String sourceCode;

    private SourceInfo sourceInfo;

    private void showView(SourceInfo sourceInfo) {
        this.sourceInfo=sourceInfo;
        tv_name.setText(sourceInfo.getProductName());
        tv_unit.setText(sourceInfo.getPackUnit());
        edit_gs_name.setText(sourceInfo.getCompanyName());
        tv_weight.setText(sourceInfo.getWeight() + sourceInfo.getUnit());
    }

    public static void show(Context context,String sourceCode) {
        Intent intent = new Intent(context, UpdateTag2Activity.class);
        intent.putExtra("sourceCode",sourceCode);
        context.startActivity(intent);
    }

    @Override
    protected boolean initArgs(Bundle bundle) {
        if(bundle!=null){
            sourceCode=bundle.getString("sourceCode");
        }
        return super.initArgs(bundle);
    }

    @Override
    protected int getLayoutSourceId() {
        return R.layout.activity_update_tag_2;
    }


    @Override
    protected void initWidgets() {
        super.initWidgets();
        mLoadManager = LoadFactory.getInstance().register(layout_base, new AbsView.OnReloadListener() {
            @Override
            public void onReload(View view) {
                mLoadManager.showStateView(LoadingView.class);
                searchInfo();
            }
        });
    }


    @Override
    protected void initData() {
        super.initData();
        if (Constants.getLocation() != null) {
            String address=Constants.getLocation().getAddress();
            if(address!=null){
                int index=address.indexOf("靠近");
                tv_address.setText(index>0?address.substring(0,index):address);
            }
        }
        onDialogNFC();
        tv_time.setText(TimeUtil.stamp2Time(System.currentTimeMillis(), Common.DateType.dateIF));
        searchInfo();
    }

    private void searchInfo() {
        AsyncOkHttpClient okHttpClient = new AsyncOkHttpClient();
        AsyncHttpPostFormData asyncHttpPostFormData = new AsyncHttpPostFormData();
        asyncHttpPostFormData.addFormData("sourceCode", sourceCode);
        okHttpClient.posts(Common.Constant.API_IP + "handle/queryBySourceCode", asyncHttpPostFormData, new AsyncResponseHandler() {
            @Override
            public void onFailure(IOException e) {
                mLoadManager.showStateView(ErrorView.class);
                e.printStackTrace();
            }

            @Override
            public void onSuccess(AsyncHttpResponse response) {
                onDismiss();
                Type type = new TypeToken<RspModel<SourceInfo>>() {
                }.getType();
                RspModel<SourceInfo> rspModel = getAnalysisBase(mLoadManager, response, type, "溯源详情");
                if (rspModel == null) {
                    return;
                }
                switch (rspModel.getCode()) {
                    case 1:
                        if (rspModel.getData() != null) {
                            showView(rspModel.getData());
                        }
                        break;
                    default:
                        mLoadManager.showStateView(ErrorView.class);
                        break;
                }
            }
        });
    }

    /**
     * 标签更换
     */
    private void updateTag(String address,String handleTime, String imageUrl, String productId,String oldSourceCode, String sourceCode,String packUnit,String unit, int weight) {
        loadingDialogShow(false);
        AsyncOkHttpClient okHttpClient = new AsyncOkHttpClient();
        AsyncHttpPostFormData asyncHttpPostFormData = new AsyncHttpPostFormData();
        asyncHttpPostFormData.addFormData("companyId",new Gson().fromJson(AccountManagers.getAccount(), FUserInfo.class).getInfo().getCompanyId());
        asyncHttpPostFormData.addFormData("address", address);//必填：地址
        asyncHttpPostFormData.addFormData("handleTime",handleTime);//必填：操作时间（格式：yyyy-MM-dd HH:mm:ss）
        asyncHttpPostFormData.addFormData("handleType", 3);//必填：经手动作（1、入库，2、开箱验货，3、标签破损）
        asyncHttpPostFormData.addFormData("imageUrl", imageUrl);//图片地址（多张图片用英文逗号隔开）
        asyncHttpPostFormData.addFormData("packUnit", packUnit);//必填：装单位（袋、箱）
        asyncHttpPostFormData.addFormData("productId", productId);//产品ID：开箱验货封箱时必填，更换标签时必填
        asyncHttpPostFormData.addFormData("productName", tv_name.getText().toString());//必填：产品名称
        asyncHttpPostFormData.addFormData("sourceCode", sourceCode);//必填：溯源码
        asyncHttpPostFormData.addFormData("oldSourceCode",oldSourceCode);//旧溯源码，开箱或更换标签时必填
        asyncHttpPostFormData.addFormData("unit", unit);//必填：重量单位（克、千克）
        asyncHttpPostFormData.addFormData("userId", AccountManagers.getUserId());//必填：会员ID
        asyncHttpPostFormData.addFormData("weight", weight);//必填：产品单位重量
        okHttpClient.posts(Common.Constant.API_IP + "handle/recordTrace", asyncHttpPostFormData, new AsyncResponseHandler() {
            @Override
            public void onFailure(IOException e) {
                onDismiss();
                App.getInstance().showMessage(getResources().getString(R.string.connection_error));
                e.printStackTrace();
            }

            @Override
            public void onSuccess(AsyncHttpResponse response) {
                onDismiss();
                Type type = new TypeToken<RspModel<String>>() {
                }.getType();
                RspModel<String> rspModel = getAnalysis(response, type, "标签更换");
                if (rspModel == null) {
                    return;
                }
                switch (rspModel.getCode()) {
                    case 1:
                        App.getInstance().showMessage("标签已更换成功！");
                        finish();
                        break;
                    default:
                        App.getInstance().showMessage(rspModel.getMessage());
                        break;
                }
            }
        });
    }


    @OnClick({R.id.layout_camera,R.id.btn_up, R.id.btn_submit})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.layout_camera:
                checkAndRequestPermission();
                break;
            case R.id.btn_up:
                UpdateTagActivity.show(mContext,sourceCode);
                finish();
                break;
            case R.id.btn_submit:
                String newCode=String.valueOf(tv_code.getText()).trim();
                if(TextUtils.isEmpty(newCode) || "".equals(newCode)){
                    App.getInstance().showMessage("请获取新的溯源码！");
                    return;
                }
                String valueAddress = String.valueOf(tv_address.getText()).trim();
                if (TextUtils.isEmpty(valueAddress)) {
                    App.getInstance().showMessage("获取地址中，请稍后！");
                    if (Constants.getLocation() != null) {
                        String address=Constants.getLocation().getAddress();
                        if(address!=null){
                            int index=address.indexOf("靠近");
                            tv_address.setText(index>0?address.substring(0,index):address);
                        }
                    }
                    return;
                }
                updateTag(valueAddress,tv_time.getText().toString(),imageUrl,sourceInfo.getProductId(),sourceInfo.getSourceCode(),newCode,sourceInfo.getPackUnit(),sourceInfo.getUnit(),sourceInfo.getWeight());
                break;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // 如果裁剪错误则直接返回不做任何操作
        if (resultCode == UCrop.RESULT_ERROR) {
            return;
        }
        // 如果有返回值
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case CAMERA_REQUEST_CODE: // 拍照
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                        cropRawPhoto(providerUri);
                    } else {
                        cropRawPhoto(mUri);
                    }
                    break;
                case GALLERY_REQUEST_CODE:// 相册选择
                    cropRawPhoto(data.getData());
                    break;
                case CROP_REQUEST_CODE:
                    Uri uri = UCrop.getOutput(data);
                    if (uri != null) {
                        upHeardImage(FileUtils.getFilePathByUri(mContext, uri),layout_camera);
                    } else {
                        App.getInstance().showMessage("获取内容为空！");
                    }
                    break;
                default:
                    break;
            }
        }
    }

    private void onCodeCheck(String sourceCode) {
        AsyncOkHttpClient okHttpClient = new AsyncOkHttpClient();
        AsyncHttpPostFormData asyncHttpPostFormData = new AsyncHttpPostFormData();
        asyncHttpPostFormData.addFormData("sourceCode", sourceCode);
        okHttpClient.posts(Common.Constant.API_IP + "handle/checkPacked", asyncHttpPostFormData, new AsyncResponseHandler() {
            @Override
            public void onFailure(IOException e) {
                e.printStackTrace();
            }

            @Override
            public void onSuccess(AsyncHttpResponse response) {
                Type type = new TypeToken<RspModel<String>>() {
                }.getType();
                RspModel<String> rspModel = getAnalysis(response, type, "标签是否已使用");
                if (rspModel == null) {
                    return;
                }
                if (rspModel.getMessage().contains("已使用")) {
                    App.getInstance().showMessage(rspModel.getMessage());
                    tv_code.setText("");
                }
            }
        });
    }

    @Override
    protected void onNewIntent(Intent intent) {
        Tag detectedTag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
        NFCResult result = resolveReadIntent(detectedTag);
        if (result != null) {
            if(result.isState()){
                tv_code.setText(result.getResult().getUid());
                onCodeCheck(result.getResult().getUid());
                if(dialog!=null){
                    dialog.dismiss();
                }
            }else {
                App.getInstance().showMessage(result.getMessage());
            }
        }
    }
}
